package com.example.chinesenation.Controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.chinesenation.Entity.*;
import com.example.chinesenation.Redis.RedisService;
import com.example.chinesenation.Response.ResultType;
import com.example.chinesenation.Response.ServerResponse;
import com.example.chinesenation.Service.*;
import com.example.chinesenation.Utils.Audience;
import com.example.chinesenation.Utils.CommonURL;
import com.example.chinesenation.Utils.JwtTokenUtil;
import com.example.chinesenation.Utils.TextTools;
import com.example.chinesenation.VO.Introduction;
import com.example.chinesenation.VO.ProvinceNationData;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sakuraFallingDown
 * @version 1.0
 * @date 2021/1/18 16:22
 */
@Controller
@ResponseBody
@RequestMapping("/map")
@CrossOrigin
public class MapController {




    private final Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private Audience audience;

    @Autowired
    private INationService nationService;

    @Autowired
    private IProvincesService provincesService;
    @Autowired
    private ICitysService citysService;
    @Autowired
    private INationPartitionService nationPartitionService;//民族分布情况
    @Autowired
    private INationAgePartitionService nationAgePartitionService;
    @Autowired
    private INationBirthStatusPartitionService nationBirthStatusPartitionService;
    @Autowired
    private INationDisableworkPartitionService nationDisableworkPartitionService;
    @Autowired
    private INationEducationPartitionService nationEducationPartitionService;
    @Autowired
    private INationIndustryPartitionService nationIndustryPartitionService;
    @Autowired
    private INationMaritalStatusPartitionService nationMaritalStatusPartitionService;

    @Autowired
    private INationCityPartitionService nationCityPartitionService;

    @Autowired
    private RedisService redisService;


    /**
     *
     * @param token 用于的token
     * @param provinceName  所要查询的省份名字
     * @return 返回值为该省份民族分布的数据
     */
    @ApiOperation("地图模块中通过某个省份获取该地区民族分布的数据接口")
    @PostMapping("/province")
    public ServerResponse<List<ProvinceNationData>> province(@RequestHeader(value = "token",required = false) String token,
                                                             @RequestParam(value = "provinceName") String provinceName)  {//查询省份，不必须拥有token

        if(token!=null&&!token.equals("")){
            String uid= JwtTokenUtil.getUserId(token,audience);
            //存入数据库，作为浏览记录，存入用户uid，pid即可
            //暂未填坑
        }
        if(provinceName==null) return ServerResponse.createErrorsResponse(ResultType.MapProvinceCanNotNull);
        List<ProvinceNationData> provinceNationDataList=new ArrayList<>();
        if(redisService!=null){
            provinceNationDataList=(List<ProvinceNationData>)redisService.get(CommonURL.MapControllerRedis
                    +CommonURL.ProvinceRedis+provinceName);
        }
        if(provinceNationDataList==null||provinceNationDataList.size()==0) {
            List<NationPartition> partitionList = nationPartitionService.findByPid(provinceName);
            double totalNumber=0;
            for (NationPartition nationPartition : partitionList) {
                totalNumber+=nationPartition.getTotalNumber();
            }//统计总人数
            provinceNationDataList=new ArrayList<>();
            List<String> nationName = partitionList.stream().map(NationPartition::getNationName).collect(Collectors.toList());
            List<String> nationIntroduction=new ArrayList<>();
            nationName.forEach(str->{
                QueryWrapper<Nation> qw=new QueryWrapper<>();
                qw.eq("nation_name",str);
                Nation one = nationService.getOne(qw);
                Introduction introduction= JSON.parseObject(one.getNationIntroduction(),Introduction.class);
                nationIntroduction.add(introduction.getNation_introduction().get(0));
            });
            List<ProvinceNationData> finalProvinceNationDataList = provinceNationDataList;
            double finalTotalNumber = totalNumber;
            partitionList.forEach(nationPartition -> {//遍历，导入相应的值
                ProvinceNationData provinceNationData=new ProvinceNationData();
                provinceNationData.setProvinceName(nationPartition.getPid());
                provinceNationData.setIntroduction(nationIntroduction.get(partitionList.indexOf(nationPartition)));
                provinceNationData.setNationName(nationPartition.getNationName());
                provinceNationData.setAllCount(""+nationPartition.getTotalNumber());
                provinceNationData.setWomanCount(nationPartition.getFemaleTotalNumber());
                provinceNationData.setManCount(""+
                        (Integer.parseInt(provinceNationData.getAllCount())
                        -Integer.parseInt(provinceNationData.getWomanCount())));

                provinceNationData.setCityTotalNumber(nationPartition.getCityTotalNumber());
                provinceNationData.setCityFemaleNumber(nationPartition.getCityFemaleNumber());
                provinceNationData.setCityMaleNumber(""+
                        (Integer.parseInt(provinceNationData.getCityTotalNumber())
                                -Integer.parseInt(provinceNationData.getCityFemaleNumber())));

                provinceNationData.setTownTotalNumber(nationPartition.getTownTotalNumber());
                provinceNationData.setTownFemaleNumber(nationPartition.getTownFemaleNumber());
                provinceNationData.setTownMaleNumber(""+
                        (Integer.parseInt(provinceNationData.getTownTotalNumber())
                                -Integer.parseInt(provinceNationData.getTownFemaleNumber())));

                provinceNationData.setVillageFemaleNumber(nationPartition.getVillageFemaleNumber());
                provinceNationData.setVillageTotalNumber(nationPartition.getVillageTotalNumber());
                provinceNationData.setVillageMaleNumber(""+
                        (Integer.parseInt(provinceNationData.getVillageTotalNumber())
                                -Integer.parseInt(provinceNationData.getVillageFemaleNumber())));

                //计算比例
                double ratio = nationPartition.getTotalNumber()/finalTotalNumber;
                int num=(int)(ratio*10000);
                provinceNationData.setRatio(1.00*num/100);

                finalProvinceNationDataList.add(provinceNationData);
            });
            provinceNationDataList=finalProvinceNationDataList;
            if(provinceNationDataList.size()!=0){
                redisService.put(CommonURL.MapControllerRedis +
                        CommonURL.ProvinceRedis+
                        provinceName,provinceNationDataList);
            }//存入redis缓存
        }
        return ServerResponse.createSuccessResponse("请求成功",provinceNationDataList);
    }

    /**
     *
     * @param token 用户token
     * @param cityName 需要查询的城市名字，不一定需要很标准，这个地方会做模糊查询
     * @return  返回数据为该城市所包含的民族信息
     */

    @PostMapping("/province/city")
    public ServerResponse<List<ProvinceNationData>> city(@RequestHeader(value = "token",required = false) String token,
                                                         @RequestParam(value = "cityName")String cityName){//查询城市，不必须拥有token

        if(token!=null&&!token.equals("")){
            String uid= JwtTokenUtil.getUserId(token,audience);
            //存入数据库，作为浏览记录，存入用户uid，pid即可
        }
        if(cityName==null) return ServerResponse.createErrorsResponse(ResultType.MapCityCanNotNull);
        List<ProvinceNationData> provinceNationDataList=new ArrayList<>();
        if(redisService!=null){//获取redis的内容
            provinceNationDataList=(List<ProvinceNationData>)redisService.get(CommonURL.MapControllerRedis
                    +CommonURL.CityRedis+cityName);
        }
        if(provinceNationDataList==null||provinceNationDataList.size()==0) {//如果redis没有该数据
            List<NationCityPartition> partitionList = nationCityPartitionService.findByCid(cityName);
            double totalNumber=0;
            for (NationCityPartition nationPartition : partitionList) {
                totalNumber+=nationPartition.getTotalNumber();
            }
            provinceNationDataList=new ArrayList<>();
            List<ProvinceNationData> finalProvinceNationDataList = provinceNationDataList;
            double finalTotalNumber = totalNumber;
            partitionList.forEach(nationCityPartition -> {
                ProvinceNationData provinceNationData=new ProvinceNationData();
                provinceNationData.setProvinceName(nationCityPartition.getCity());

                provinceNationData.setNationName(nationCityPartition.getNationName());
                provinceNationData.setAllCount(""+nationCityPartition.getTotalNumber());
                double ratio = nationCityPartition.getTotalNumber()/finalTotalNumber;
                int num=(int)(ratio*10000);
                provinceNationData.setRatio(1.00*num/100);//计算该民族占所有人数的百分比

                finalProvinceNationDataList.add(provinceNationData);
            });
            provinceNationDataList=finalProvinceNationDataList;
            if(provinceNationDataList.size()!=0){
                redisService.put(CommonURL.MapControllerRedis +
                        CommonURL.CityRedis+
                        cityName,provinceNationDataList);
            }
        }
        return ServerResponse.createSuccessResponse("请求成功",provinceNationDataList);
    }

    /**
     *
     * @return 返回中国所有省份
     */
    @PostMapping("/provinceData")
    public ServerResponse<List<String>> provinceData(){


        List<Provinces> provinces=provincesService.list();
        List<String> provinceList=provinces.stream().map(Provinces::getProvince).collect(Collectors.toList());
        return ServerResponse.createSuccessResponse("请求成功",provinceList);
    }

    /**
     *
     * @param province 省份名字
     * @return 返回当前省份的所有城市
     */
    @PostMapping("/cityData")
    public ServerResponse<List<String>> provinceData(@RequestParam("province")String province){

        QueryWrapper<Provinces> qw=new QueryWrapper<>();
        qw.eq("province",province);

        List<Provinces> provinces=provincesService.list(qw);
        QueryWrapper<Citys> qwc=new QueryWrapper<>();
        qwc.eq("pid",provinces.get(0).getPid());
        List<Citys> citys=citysService.list(qwc);
        List<String> city = citys.stream().map(Citys::getCity).collect(Collectors.toList());
        return ServerResponse.createSuccessResponse("请求成功",city);
    }




}
